package com.ang.jdk8.optional;

import java.util.Optional;

/**
 * @author ssang
 * @date 2021-09-18 17:06
 */
public class OptionalTest {

    public static void main(String[] args) {
        OptionalTest t = new OptionalTest();
        t.test01();
    }

    /**
     * .map
     * .orElse
     * map()里面，可以用o.getXXX来获取值，如果有get方法的话
     */
    public void test01(){
        Child child = new Child("jim",10);

        //所有属性都不为null
        User u1 = new User("1","ang","男",child);
        Optional<User> optionalUser1 = Optional.ofNullable(u1);

        //2个属性为null
        User u2 = new User("1",null,"男",null);
        Optional<User> optionalUser2 = Optional.ofNullable(u2);

        String name1 = optionalUser1
                .map(o->o.name)
                .orElse("-");
        String name2 = optionalUser2
                .map(o->o.name)
                .orElse("-");

        System.out.println("user的name赋值为："+name1);
        System.out.println("user的name赋值为："+name2);

        //.map可以使用链式，循环遍历对象的对象
        String childName1 = optionalUser1
                .map(o->o.child)
                .map(c->c.name)
                .orElse("-");
        String childName2 = optionalUser2
                .map(o->o.child)
                .map(c->c.name)
                .orElse("-");

        System.out.println("user的child的name，赋值为："+childName1);
        System.out.println("user的child的name，赋值为："+childName2);

        //ifPresent()的使用
        Optional<Child> child1 = optionalUser1.map(o->o.child);
        child1.ifPresent(o-> System.out.println(String.format("child对象存在，name：",o.name)));

        //isPresent()的使用
        if(child1.isPresent()){
            System.out.println("child对象存在");
        }else{
            System.out.println("child对象不存在");
        }
    }

    //********************************************************
    //内部类
    //********************************************************
    class User{
        String id;
        String name;
        String sex;
        Child child;

        public User(String id, String name, String sex, Child child) {
            this.id = id;
            this.name = name;
            this.sex = sex;
            this.child = child;
        }
    }

    class Child{
        String name;
        int age;

        public Child(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
}
